<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class UserInfo extends Model
{

    /**
     * 设置微信信息
     * @param $user_id
     * @param array $options
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function wxInfo($user_id, $options=[]){
        $user = User::find($user_id);
        $res = self::where(['openid'=>$options['openid']])->find();
        if(!$user) return 0;
        if($res && ($user_id != $res->user_id)) return -1;
        if($res){
            return 1;
        }else{
            $data = [
                'user_id'=>$user_id,
                'openid'=>$options['openid'],
                'session_key'=>$options['session_key'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            $r = self::insert($data);
            //默认成为达人
            UserRole::insert(['uid'=>$user_id, 'rid'=>5]);
            //保存unid
            $user->save(['wx_unid'=>$options['unionid']]);
            if($r){
                return 1;
            }else{
                return 0;
            }
        }
    }
}
